package wsBroker

import (
	"context"
	"github.com/gorilla/websocket"
	"t11Lib/t11Errors"
	"t11Lib/t11Log"
	"time"
)

//controller中的连接信息
func NewWsConnector(conn *websocket.Conn) *WsConnector {
	return &WsConnector{
		conn:      conn,
		writeChan: make(chan string),
	}
}

type WsConnector struct {
	conn      *websocket.Conn
	writeChan chan string
}

func (self *WsConnector) ReadRoutine(ctx context.Context) {
	ctx, cancel := context.WithCancel(ctx)
	defer func() {
		t11Log.Debug("ReadRoutine退出")
		_ = self.conn.Close()
		cancel()
	}()
	for {
		dataType, data, err := self.conn.ReadMessage()
		if err != nil || dataType != websocket.TextMessage {
			return
		}
		text := string(data)
		t11Log.Debug("收到数据", text)
		err = self.WriteData(ctx, text)
		if err != nil {
			return
		}
	}
}

func (self *WsConnector) WriteData(ctx context.Context, text string) t11Errors.T11Error {
	ctx, _ = context.WithTimeout(ctx, time.Second*10)
	select {
	case self.writeChan <- text:
		return nil
	case <-ctx.Done():
		return t11Errors.New("write canceled")
	}
}
func (self *WsConnector) WriteRoutine(ctx context.Context) {
	ctx, cancel := context.WithCancel(ctx)
	defer func() {
		t11Log.Debug("WriteRoutine退出")
		cancel()
		_ = self.conn.Close()
	}()
	for {
		select {
		case <-ctx.Done():
			return
		case data := <-self.writeChan:
			err := self.conn.WriteMessage(websocket.TextMessage, []byte(data))
			if err != nil {
				return
			}
			break
		}
	}
}
